from io import BytesIO

from flask import render_template, make_response, session, request, jsonify, redirect
from werkzeug.security import generate_password_hash, check_password_hash

from moldels import db
from moldels.index import Users
from utils.captcha.capthca_utils import create_code
from views import user_blu


@user_blu.route("/login.html", methods=["POST", "GET"])
def login():
    re_type = request.method

    if re_type == "GET":

        return render_template("index/login.html")

    else:

        # active = request.json.get("active")

        # 登录

        phone = request.json.get("phone")
        password = request.json.get("password")
        mi_code = request.json.get("mi_code")

        # 图片验证码验证
        re_code = session.get('captcha_code')
        if not re_code == mi_code.upper():
            ret = {
                "errno": '1122',
                "errmsg": "验证码错误"
            }
            return jsonify(ret)
        # 数据库查询

        user = db.session.query(Users).filter(Users.mobile == phone).first()

        if user and check_password_hash(user.password_hash, password):
            # 保持登录状态
            session["user_id"] = user.id

            ret = {
                "errno": "0",
                "errmsg": "成功"
            }
        else:
            ret = {
                "errno": "101",
                "errmsg": "用户名密码错误"
            }

    return jsonify(ret)


@user_blu.route("/register.html", methods=["POST", "GET"])
def register():
    re_type = request.method

    if re_type == "GET":
        return render_template("index/register.html")

    else:

        # 获取数据
        name = request.json.get("name")
        phone = request.json.get("phone")
        password = request.json.get("password")
        # 手机验证码
        phone_code = request.json.get("mi_code")

        print(phone_code)
        # 验证手机验证码
        note_code = session.get("note_code")

        if int(note_code) != int(phone_code):
            ret = {
                "errno": "6544",
                "errmsg": "手机验证码错误"
            }

            return jsonify(ret)

        # 密码加密
        password_hash = generate_password_hash(password)

        # 检验数据合法性

        # 判断有无
        user = db.session.query(Users).filter(Users.mobile == phone).first()

        if user:
            ret = {
                "errno": "100",
                "errmsg": "手机号已经注册，请直接登录"
            }

            return jsonify(ret)

        # 存入数据库
        user = Users(nick_name=name, password_hash=password_hash, mobile=phone)

        db.session.add(user)
        db.session.commit()

        ret = {
            "errno": '0',
            "errmsg": "注册成功"
        }
        # 报错登录状态
        session["user_id"] = user.id

        return jsonify(ret)


@user_blu.route("/reset.html", methods=["POST", "GET"])
def reset():
    type = request.method

    if type == "GET":
        return render_template("index/reset.html")

    elif type == "POST":

        phone = request.json.get("phone")

        password = request.json.get("password")

        mi_code = request.json.get("mi_code")

        # 用户查询验证
        try:

            user = db.session.query(Users).filter(Users.mobile == phone).first()
            if user:

                # 手机验证码验证

                # 密码加密
                password_hash = generate_password_hash(password)
                # 修改密码
                user.password_hash = password_hash

                db.session.commit()

                ret = {
                    "errno": '0',
                    "errmsg": "成功"
                }
            else:

                ret = {
                    "errno": "201",
                    "errmsg": "还未注册"
                }

        except Exception as e:
            print(e)
            ret = {
                "errno": "300",
                "errmsg": "请重新申请"

            }

    else:

        ret = {
            "errno": "101",
            "errmsg": "请求失败"
        }

    return jsonify(ret)


@user_blu.route("/image_code")
def image_code():
    # 调用方法拿到数据
    code_str, image = create_code()

    buf = BytesIO()  # 生成 二进制数据对象 直接使用 不用生成图片

    # 把图片数据存到 buf中
    image.save(buf, 'jpeg')

    # 从 buf 里获取 图片的二进制数据
    img_data = buf.getvalue()

    # 创建 response 对象
    ret = make_response(img_data)

    buf.close()

    ret.headers['Content-Type'] = 'image/jpg'

    # 设置session 用来后期验证
    session['captcha_code'] = code_str.upper()

    return ret


@user_blu.route("/logout")
def logout():
    session.clear()

    return redirect('/')
